package com.itheima.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.core.controller.BaseController;
import com.itheima.common.core.domain.AjaxResult;
import com.itheima.common.core.page.TableDataInfo;
import com.itheima.server.domain.Course;
import com.itheima.server.dto.CourseInsertDto;
import com.itheima.server.dto.CourseQueryDto;
import com.itheima.server.service.CourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/clues/course")
public class CourseController extends BaseController {

    @Autowired
    CourseService courseService;


    @GetMapping("/list")
    public TableDataInfo list(CourseQueryDto dto){

       return this.getDataTable(courseService.pageQuery(dto));

    }


    @PostMapping
    public AjaxResult add(@RequestBody CourseInsertDto dto){
        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        Course course = new Course();
        BeanUtils.copyProperties(dto,course);
        course.setCode(code);
        courseService.save(course);
        return success();
    }


    @DeleteMapping("/{ids}")
    public AjaxResult delete(@PathVariable String ids){
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        courseService.removeByIds(list);
        return success();
    }


    @PutMapping
    public AjaxResult update(@RequestBody Course course){
        courseService.updateById(course);
        return success();
    }


    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Integer id){
        Course course = courseService.getById(id);
        return success(course);
    }

    @GetMapping("/listselect")
    public AjaxResult getCourseListBySubject(Integer subject){
        List<Course> list = null;
        if (ObjectUtils.isEmpty(subject)){
            list = courseService.list();
        } else {
            LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Course::getSubject,subject);
            list = courseService.list(wrapper);
        }
        return success(list);
    }



}
